<template>
    <div class="common-list comp-clients" :class="{ 'comp-clients--depts': !role || role === 'holder' || role === 'officer' }" v-loading.fullscreen="loading">
        <div class="depts" v-if="!role || role === 'holder' || role === 'officer'">
            <div class="dept dept--lv0">
                <div class="name">组织架构</div>
            </div>
            <template v-for="dept1 in depts">
                <div class="dept dept--lv1" :key="" :class="{ expanded: dept1.expanded, selected: dept1.id === filters.deptId }">
                    <div class="expand" @click="expandDept(dept1)"></div>
                    <div class="name" @click="selectDept(dept1)">
                        <div class="text" >{{ dept1.name }}</div>
                        <div class="flag" v-if="dept1.type">{{ dept1.typeText }}</div>
                    </div>
                </div>
                <template v-for="dept2 in dept1.depts">
                    <div class="dept dept--lv2" :key="" :class="{ expanded: dept2.expanded, selected: dept2.id === filters.deptId }" v-if="dept1.expanded">
                        <div class="expand" @click="expandDept(dept2)"></div>
                        <div class="name" @click="selectDept(dept2)">
                            <div class="text">{{ dept2.name }}</div>
                            <div class="flag" v-if="dept2.type">{{ dept2.typeText }}</div>
                        </div>
                    </div>
                    <template v-for="dept3 in dept2.depts">
                        <div class="dept dept--lv3" :key="" :class="{ expanded: dept3.expanded, selected: dept3.id === filters.deptId }" v-if="dept1.expanded && dept2.expanded">
                            <div class="expand" @click="expandDept(dept3)"></div>
                            <div class="name" @click="selectDept(dept3)">
                                <div class="text">{{ dept3.name }}</div>
                                <div class="flag" v-if="dept3.type">{{ dept3.typeText }}</div>
                            </div>
                        </div>
                        <template v-for="dept4 in dept3.depts">
                            <div class="dept dept--lv4" :key="" :class="{ expanded: dept4.expanded, selected: dept4.id === filters.deptId }" v-if="dept1.expanded && dept2.expanded && dept3.expanded">
                                <div class="expand" @click="expandDept(dept4)"></div>
                                <div class="name" @click="selectDept(dept4)">
                                    <div class="text">{{ dept4.name }}</div>
                                    <div class="flag" v-if="dept4.type">{{ dept4.typeText }}</div>
                                </div>
                            </div>
                            <template v-for="dept5 in dept4.depts">
                                <div class="dept dept--lv5" :key="" :class="{ expanded: dept5.expanded, selected: dept5.id === filters.deptId }" v-if="dept1.expanded && dept2.expanded && dept3.expanded && dept4.expanded">
                                    <div class="expand" @click="expandDept(dept5)"></div>
                                    <div class="name" @click="selectDept(dept5)">
                                        <div class="text">{{ dept5.name }}</div>
                                        <div class="flag" v-if="dept5.type">{{ dept5.typeText }}</div>
                                    </div>
                                </div>
                            </template>
                        </template>
                    </template>
                </template>
            </template>
        </div>
        <div class="common-list__head">
            <el-input class="filter" v-model="filters.number" size="small" style="width: 240px" clearable placeholder="请输入" :readonly="loading" @change="search(true)">
                <span slot="prepend">工号</span>
            </el-input>
            <el-input class="filter" v-model="filters.name" size="small" style="width: 240px" clearable placeholder="请输入" :readonly="loading" @change="search(true)">
                <span slot="prepend">姓名</span>
            </el-input>
            <!-- <el-select class="filter" v-model="filters.sex" size="small" style="width: 140px" @change="search(true)">
                <el-option label="不限性别" :value="null"></el-option>
                <el-option v-for="data in env.userSexs" :key="data.id" :label="data.name" :value="data.value"></el-option>
            </el-select> -->
            <el-input class="filter" v-model="filters.mobile" size="small" style="width: 240px" clearable placeholder="请输入" :readonly="loading" @change="search(true)">
                <span slot="prepend">手机号</span>
            </el-input>
            <el-select class="filter" v-model="filters.role" size="small" style="width: 140px" @change="search(true)" v-if="!role">
                <el-option label="不限角色" :value="null"></el-option>
                <el-option key="100" label="服务专员" value="holder">服务专员</el-option>
                        <el-option key="300" label="后援服务单位" value="officer">后援服务单位</el-option>
                <!-- <el-option v-for="data in env.userRoles" :key="data.id" :label="data.name" :value="data.value"></el-option> -->
            </el-select>
            <el-select class="filter" v-model="filters.banned" size="small" style="width: 140px" @change="search(true)">
                <el-option label="不限冻结状态" :value="null"></el-option>
                <el-option v-for="data in env.userBanneds" :key="data.id" :label="data.name" :value="data.value"></el-option>
            </el-select>
            <el-select class="filter" v-model="filters.flag" size="small" style="width: 140px" @change="search(true)">
                <el-option label="不限激活状态" :value="null"></el-option>
                <el-option v-for="data in env.userEnable" :key="data.id" :label="data.name" :value="data.value"></el-option>
            </el-select>
            <el-button class="filter" type="primary" size="small" @click="activation()">一键激活</el-button>

            <el-button class="filter" type="primary" size="small" @click="search()">查询</el-button>
            <el-button class="filter" type="plain" size="small" @click="reset(true)">重置</el-button>
        </div>
        <div class="common-list__nect">
            <slot name="head" :loading="loading" :filters="filters" :selects="selects"></slot>
        </div>
        <div class="common-list__body">
            <el-table ref="table" size="medium" height="100%" :data="list" @header-click="onTableHeaderClick" @row-click="onTableRowClick" @selection-change="onTableSelectionChange">
                <el-table-column type="selection" align="center" v-if="select"></el-table-column>
                <el-table-column label="头像/姓名/工号" min-width="8">
                    <template #default="scope">
                        <div>

                            <img v-if="scope.row.avatar" style="float: left; margin-right: 10px; border-radius: 20px; width: 40px; height: 40px" :src="scope.row.avatar"/>
                            <img  v-else style="float: left; margin-right: 10px; border-radius: 20px; width: 40px; height: 40px" src="../assets/user-avatar.png"/>
                        </div>

                        <a :href="'#/org/client?clientId=' + scope.row.id" v-if="link && access('org')">{{ scope.row.name }}</a>
                        <span v-else>{{ scope.row.name }}</span>
                        <div style="margin-left: 50px; color: #aaa">{{ scope.row.number }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="性别" min-width="2">
                    <template #default="scope">{{ scope.row.sexText }}</template>
                </el-table-column>
                <el-table-column label="手机号" min-width="6">
                    <template #default="scope">{{ scope.row.mobile || "-" }}</template>
                </el-table-column>
                <el-table-column label="角色" min-width="4" v-if="!role">
                    <template #default="scope">{{ scope.row.roleText }}</template>
                </el-table-column>
                <el-table-column label="所属部门" min-width="12" v-if="!role || role === 'holder' || role === 'officer'">
                    <template #default="scope">
                        <template v-if="scope.row.depments.length > 0">
                            <div v-for="depment in scope.row.depments" :key="depment.id">
                                <span>{{ depment.dept.name }}</span>
                                <span> - </span>
                                <span>{{ depment.duty }}</span>
                            </div>
                        </template>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="所属单位" min-width="12" v-if="!role || role === 'holder' || role === 'officer'">
                    <template #default="scope">
                        <template v-if="scope.row.dapments.length > 0">
                            <div v-for="dapment in scope.row.dapments" :key="dapment.id">
                                <span>{{ dapment.dapt.name }}</span>
                                <span> - </span>
                                <span>{{ dapment.duty }}</span>
                            </div>
                        </template>
                        <span v-else>-</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="冻结状态" min-width="4">
                    <template #default="scope">
                        <span class="el-status--danger" v-if="scope.row.banned === 'yes'"></span>
                        <span class="el-status--success" v-else-if="scope.row.banned === 'not'"></span>
                        <span>{{ scope.row.bannedText }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="激活状态" min-width="4">
                    <template #default="scope">
                        <span class="el-status--danger" v-if="scope.row.flag === 'not'"></span>
                        <span class="el-status--success" v-else-if="scope.row.flag === 'yes'"></span>
                        <span>{{ scope.row.bandFlag }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="最近活跃时间" min-width="6">
                    <template #default="scope">{{ scope.row.lastActiveAt || "-" }}</template>
                </el-table-column>
                <el-table-column label="操作" width="160" v-if="$slots.body || $scopedSlots.body">
                    <template #default="scope">
                        <slot name="body" :loading="loading" :filters="filters" :data="scope.row" :selects="selects"></slot>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="common-list__foot" :class="{ 'common-list__foot--slot': $slots.foot || $scopedSlots.foot }">
            <el-pagination background layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 50, 100]" :page-size="filters.linage" :current-page="filters.page" :total="filters.total" @size-change="onTableLinageChange" @current-change="onTablePageChange"></el-pagination>
            <slot name="foot" :loading="loading" :filters="filters" :selects="selects"></slot>
        </div>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { object, array, string, int, session } from "../util";
    export default {
        name: "comp-clients",
        mixins: [mixin],
        props: {
            role: { type: String, default: null },
            select: { type: Boolean, default: false },
            link: { type: Boolean, default: false },
        },
        data: () => ({
            loading: false,
            filters: {
                ids: null,
                number: null,
                name: null,
                sex: null,
                mobile: null,
                role: null,
                deptId: null,
                banned: 'not',
                flag: 'yes',
                linage: 10,
                page: 1,
                total: 0,
            },
            list: [],
            selects: [],
            depts: [],
            num:null

        }),
         mounted(){
           this.num =  this.generateRandomNumber(10);
        //    console.log(res);
        },
        methods: {
                 generateRandomNumber(digit) { //若为4
                const min = Math.pow(20, digit - 1) // 最小值，即1000
                const max = Math.pow(20, digit) - 1 // 最大值，即9999
                const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min
                return randomNumber.toString()
                },
            activation(){
                if (this.loading) return;
                if (!this.filters.ids ||this.filters.ids.length==0) return this.plugins.modal.toast("请先勾选要激活的用户哦！", "warning");
                // let content = " <span style='color:red;'>" + (orders.length > 1 ? "勾选的" + orders.length + "个事项" : orders[0].title) + "</span> 吗？";
                this.plugins.modal.alert("", "确定激活这些用户", "warning", ["确定激活", "再想想"]).then((ok) => {
                    if (!ok){
                        // this.filters.ids =null;
                       return;
                    }
                    this.loading = true;
                    this.plugins.user.activationfun(this.filters.ids).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("激活成功！", "success");
                            this.search();
                        } else {
                            this.plugins.modal.alert("激活失败", res.code + "：" + res.msg, "error");
                        }
                    });
                });
                    // console.log(this.filters.ids);
            },
            reset(deep) {
                let data = deep ? {} : object(session([this.env.key, this.$options.name, "filters", this.$route.fullPath]));
                this.filters = Object.assign(this.$options.data().filters, data);
                this.filters.deptId = null;
                this.search(true);
            },
            validate() {
                let filters = this.filters;
                filters.ids = null;
                filters.role = this.role || filters.role;
                filters.total = Math.max(int(filters.total), 0);
                filters.linage = Math.max(int(filters.linage), 1);
                filters.page = Math.max(Math.min(int(filters.page), Math.ceil(filters.total / filters.linage)), 1);
                session([this.env.key, this.$options.name, "filters", this.$route.fullPath], filters);
            },
            onTableHeaderClick() {
                this.select && this.$refs.table.toggleAllSelection();
            },
            onTableRowClick(row) {
                this.select && this.$refs.table.toggleRowSelection(row);
            },
            onTableLinageChange(value) {
                this.filters.linage = value;
                this.search(true);
            },
            onTablePageChange(value) {
                this.filters.page = value;
                this.search(true);
            },
            onTableSelectionChange(selects) {
                // console.log(selects);
                let weijiselects = selects.filter(item =>item.flag == "not")
                if(selects.length===0){
                    this.filters.ids = null
                }
                console.log(weijiselects);
                this.filters.ids = weijiselects.map((data) => data.id);
                // console.log(this.filters.ids);
                this.selects = selects;
            },
            expandDept(dept) {
                if (dept.expanded) {
                    dept.expanded = false;
                } else if (dept.loaded) {
                    dept.expanded = true;
                } else {
                    this.loading = true;
                    this.plugins.user.getDeptsother({ deptId: dept.id, linage: 1000, page: 1 }).then((res) => {
                        // console.log(res,123);
                        this.loading = false;
                        if (res.code === 0) {
                            dept.depts = res.data.list;
                            dept.depts.forEach((item) => {
                                item.dept.name = dept.name;
                                item.level = dept.level + 1;
                            });
                            dept.depts.sort((a, b) => {
                                let a1 = a.city.id;
                                let a2 = a.county.id;
                                let a3 = a.sort;
                                let b1 = b.city.id;
                                let b2 = b.county.id;
                                let b3 = b.sort;
                                return a1 === b1 ? a2 === b2 ? b3 - a3 : a2 - b2 : a1 - b1;
                            });
                            dept.expanded = true;
                            dept.loaded = true;
                        } else {
                            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                }
            },
            selectDept(dept) {
                this.filters.deptId = this.filters.deptId === dept.id ? "" : dept.id;
                this.search(true);
            },
            search(clean) {
                if (this.loading) return;
                if (clean) this.list = [];
                if (clean) this.selects = [];
                let filters = this.filters;
                this.validate();
                this.loading = true;
                this.plugins.user.getClients(filters).then((res) => {
                    this.loading = false;
                    this.list = [];
                    this.selects = [];
                    this.$nextTick(() => this.$refs.table.doLayout());
                    if (res.code === 0) {
                        let data = res.data;
                        if (data.page > 1 && data.list.length === 0) {
                            filters.total = 0;
                            this.search();
                        } else {
                            filters.total = data.total;
                            this.list = data.list;
                            this.validate();
                        }
                    } else {
                        filters.total = 0;
                        this.validate();
                        this.plugins.modal.toast("列表加载失败<br>" + res.code + "：" + res.msg, "error");
                    }
                });
            },
            init() {
                this.loading = true;
                this.plugins.user.call(async () => {
                    let length = this.depts.length;
                    if (length === 0) this.depts = this.role && this.role === "staff" ? [] : await this.plugins.user.getDeptsother({ level: 1, linage: 1000, page: 1 }).then((res) => array(() => res.data.list).sort((a, b) => b.sort - a.sort));
                    return { code: 0 };
                }).then((res) => {
                    this.loading = false;
                    this.reset();
                });
            },
        },
    };
</script>

<style lang="scss">
    .comp-clients {
        overflow: hidden;
    }

    .comp-clients--depts {
        padding-left: 302px;

        & > .depts {
            position: absolute;
            top: 0;
            left: 0;
            border: solid 1px #ddd;
            width: 280px;
            height: calc(100% - 2px);
            overflow-x: hidden;
            overflow-y: auto;
            scrollbar-width: none;

            &::-webkit-scrollbar {
                width: 6px;
                height: 1px;
            }

            &::-webkit-scrollbar-track {
                background-color: transparent;
            }

            &::-webkit-scrollbar-thumb {
                background-color: #ddd;
            }

            & > .dept {
                display: flex;
                align-items: flex-start;
                border-bottom: dashed 1px #ddd;
                user-select: none;
                cursor: pointer;

                & > .expand {
                    flex: 0 0 auto;
                    padding: 6px;
                    width: 20px;
                    height: 20px;
                    color: #aaa;
                    font-size: 16px;
                    line-height: 20px;
                    text-align: center;
                    user-select: none;
                    cursor: pointer;

                    &:before {
                        content: "+";
                    }
                }

                & > .name {
                    flex: 1 1 0;
                    display: flex;
                    align-items: flex-start;
                    padding: 7px 6px 7px 0;

                    & > .text {
                        flex: 0 1 auto;
                        min-height: 18px;
                        color: #333;
                        font-size: 14px;
                        line-height: 18px;
                    }

                    & > .flag {
                        flex: 0 0 auto;
                        margin-left: 0.5em;
                        height: 18px;
                        color: #999;
                        font-size: 14px;
                        line-height: 18px;
                    }
                }

                &.expanded {
                    & > .expand {
                        &:before {
                            content: "-";
                        }
                    }
                }

                &.selected {
                    background-color: #d9e5f5;

                    & > .name {
                        color: #1677ff;
                    }
                }
            }

            & > .dept--lv0 {
                position: sticky;
                top: 0;
                left: 0;
                z-index: 1;
                background-color: white;

                & > .name {
                    display: block;
                    height: 18px;
                    color: #333;
                    font-size: 14px;
                    font-weight: bold;
                    line-height: 18px;
                    text-align: center;
                }
            }

            & > .dept--lv1 {
                margin-left: 0;
            }

            & > .dept--lv2 {
                margin-left: 28px;
            }

            & > .dept--lv3 {
                margin-left: 56px;
            }

            & > .dept--lv4 {
                margin-left: 84px;
            }

            & > .dept--lv5 {
                margin-left: 112px;
            }
        }
    }
</style>
